/* Copyright (c) 2008, Antonie Jovanoski
 *	
 * All rights reserved.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "qtwitupdate.h"

QTwitUpdate::QTwitUpdate(QObject *parent)
:	QTwitBase(parent)
{
}

//TODO: checking 140 characters

void QTwitUpdate::setUpdate(const QString &update)
{
	QNetworkRequest req(QUrl("https://twitter.com/statuses/update.xml"));

	QByteArray header("Authorization");
	QByteArray userpass;
	userpass.append(m_username.toUtf8());
	userpass.append(":");
	userpass.append(m_password.toUtf8());

	QByteArray userpass64enc = userpass.toBase64();
	
	QByteArray basicAuth("Basic ");
	basicAuth.append(userpass64enc);

	req.setRawHeader(header, basicAuth);

	QByteArray status("status=");
	QByteArray messageStatus(update.toUtf8());
	status.append(messageStatus.toPercentEncoding());

	m_netManager.post(req, status);
}

void QTwitUpdate::reply(QNetworkReply *reply)
{
	if(reply->error() != QNetworkReply::NoError)
		return;

	QByteArray output = reply->readAll();

	QBuffer outputBuffer(&output);
	outputBuffer.open(QIODevice::ReadOnly);

	QXmlQuery query;
	query.bindVariable("inputDocument", &outputBuffer);
	query.setQuery("declare variable $inputDocument external; doc($inputDocument)/status/string(text)");

	QStringList result;

	if(!query.evaluateTo(&result))
		return;

	reply->deleteLater();

	//TODO: Check result

	emit finished();
}
